import axios from 'axios';

const req = (method, url, params) => {
    console.log({ file: params }, 'params');
    const formData = new FormData();
    formData.append('file', params);
    console.log({ param: formData.get('params') }, 'formData');
    for (const key in params) {
        if (key == 'file') {
            formData.append(key, params[key]);
        }
    }

    const headers = {
        'Content-Type': 'multipart/form-data',
        token: JSON.parse(sessionStorage.getItem('logintoken'))
    }

    return axios({
        method: method,
        url: url,
        headers: headers,
        data: formData
    }).then(res => {
        return res.data;
    }).catch(err => {
        return err.response.data;
    });
};

const reqs = (method, url, files) => {
    const headers = {
        'Content-Type': 'multipart/form-data',
        token: JSON.parse(sessionStorage.getItem('logintoken'))
    };

    return axios({
        method: method,
        url: url,
        headers: headers,
        data: files
    }).then(res => {
        return res.data;
    }).catch(err => {
        return err.response.data;
    });
};

const reqsDel = (method, url, id) => {
    const fullUrl = `${url}?id=${encodeURIComponent(id)}`; // 确保ID被正确编码

    const headers = {
        'Content-Type': 'application/json',
        token: JSON.parse(sessionStorage.getItem('logintoken'))
    };

    return axios({
        method: method,
        url: fullUrl,
        headers: headers,
        data: { id: id }
    }).then(res => {
        return res.data;
    }).catch(err => {
        return err.response.data;
    });
};
const reqPermissionList = (method, url, params) => {

    console.log(params);
    const headers = {
        'Content-Type': 'application/json',
        token: JSON.parse(sessionStorage.getItem('logintoken'))
    };

    return axios({
        method: method,
        url: url,
        headers: headers,
        data: params
    }).then(res => {
        return res.data;
    }).catch(err => {
        return err.response.data;
    });

}
const reqRoleList = (method, url, params) => {

    console.log(params);
    const headers = {
        'Content-Type': 'application/json',
        token: JSON.parse(sessionStorage.getItem('logintoken'))
    };

    return axios({
        method: method,
        url: url,
        headers: headers,
        data: params
    }).then(res => {
        return res.data;
    }).catch(err => {
        return err.response.data;
    });

}
// const reqDownloadFile = (method, url, params) => {
//     console.log(params.showFilePath);
//     const headers = {
//         'Content-Type': 'application/octet-stream',
//         token: JSON.parse(sessionStorage.getItem('logintoken'))
//     };

//     return axios({
//         method: method,
//         url: url,
//         headers: headers,
//         responseType: 'blob'
//     }).then(response => {
//         // 创建Blob对象
//         const blob = new Blob([response.data], { type: 'application/octet-stream' });

//         // 创建下载链接
//         const blobUrl = window.URL.createObjectURL(blob);
//         const downloadLink = document.createElement('a');
//         downloadLink.href = `${params.showFilePath}`;
//         downloadLink.download = `${params.fileName}`; // 设置下载的文件名

//         // 触发下载
//         downloadLink.click();

//         // 清理URL对象
//         window.URL.revokeObjectURL(blobUrl);
//     }).catch(err => {
//         console.error('Download error:', err.response.data);
//     });
// };
const reqDownloadFile = (method, url, params) => {
    const fullUrl = `${url}?id=${encodeURIComponent(params)}`;
    const headers = {
        'Content-Type': 'application/json',
        token: JSON.parse(sessionStorage.getItem('logintoken'))
    };

    return axios({
        method: method,
        url: fullUrl,
        headers: headers,
        responseType: 'blob', // 设置响应类型为blob
        data: { id: params } // 如果需要在请求体中传递参数
    }).then(response => {
        // 获取服务器返回的文件名
        const fileName = response.headers['content-disposition'].split('filename=')[1] || 'downloaded_file';
        // 创建Blob对象
        const blob = new Blob([response.data], { type: 'application/octet-stream' });
        // 创建下载链接
        const blobUrl = window.URL.createObjectURL(blob);
        const downloadLink = document.createElement('a');
        downloadLink.href = blobUrl;
        downloadLink.download = decodeURIComponent(fileName) // 设置下载的文件名

        // 触发下载
        downloadLink.click();

        // 清理URL对象
        window.URL.revokeObjectURL(blobUrl);
    }).catch(error => {
        console.error('Download error:', error);
    });
};
export const deptSave = (params) => {
    return req("post", "/api/files/upload", params);
};
// export const deptSaves = (params) => {
//     return reqs("post", "/api/files/batchUpload", params);
// };
export const deptSaves = (params) => {
  return reqs("post", "/api/files/batchUploadOther", params);
};
export const reqsDelete = (params) => {
    return reqsDel("delete", "/api/files/delete", params);
};
export const permissionList = (params) => {
    console.log(JSON.stringify(params),'查询per参数')
    return reqPermissionList("get", "/api/permission/list", params)
};
export const roleList = (params) => {
    return reqRoleList("get", "/api/role/list", params)
};
export const downloadFile = (params) => {
    return reqDownloadFile("get", "/api/files/download", params)
};
